package me.out1kiss.generate;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Hashtable;

/**
 * Created by hx-pc on 17-8-14.
 */
public class Generate2Dimension {

    public static BufferedImage generate(String text, int width, int height, BarcodeFormat barcodeFormat) {
        try {
            Hashtable hints= new Hashtable();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            if(!Files.exists(Paths.get("img"))) {
                Files.createDirectory(Paths.get("img"));
            }
            BitMatrix bitMatrix = new MultiFormatWriter().encode(text, barcodeFormat, width, height,hints);
            return MatrixToImageWriter.toBufferedImage(bitMatrix);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String []args)throws Exception{
        BufferedImage bufferedImage = generate("你好", 100, 100, BarcodeFormat.QR_CODE);
        ImageIO.write(bufferedImage, "png", new File("img/out.png"));
    }

}
